package com.nmgsr.ptmsapp.view;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.lxj.xpopup.core.CenterPopupView;
import com.maning.updatelibrary.InstallUtils;
import com.nmgsr.beans.responsedao.UpdateRes;
import com.nmgsr.nettools.util.ToastUtil;
import com.nmgsr.ptmsapp.R;
import com.qmuiteam.qmui.widget.QMUIProgressBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.io.File;

public class UpdateDialog extends CenterPopupView {

    private TextView tv_description;
    private QMUIRoundButton btn_update, btn_cancel;
    private QMUIProgressBar rectProgressBar;


    private Context context;
    private UpdateRes updateRes;
    private boolean hasCancel=true;
    private String title;
    private TextView tv_title;
    public UpdateDialog(@NonNull Context context, String title, UpdateRes updateRes, Boolean hasCancel) {
        super(context);
        this.context = context;
        this.title = title;
        this.updateRes = updateRes;
        this.hasCancel = hasCancel;

    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_activity_update;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        tv_title = findViewById(R.id.tv_title);
        tv_description = findViewById(R.id.tv_description);
        btn_update = findViewById(R.id.btn_update);
        btn_cancel = findViewById(R.id.btn_cancel);
        if (hasCancel){
            btn_cancel.setVisibility(GONE);
//            btn_update.setGravity(Gravity.CENTER);
        }
        rectProgressBar = findViewById(R.id.rectProgressBar);
        tv_title.setText(title);
        //tv_description.setText(updateRes.getDescription());
        tv_description.setText("新版本，提升了使用体验");
        btn_update.setOnClickListener(v -> {
            checkInstallPermission();
        });
        btn_cancel.setOnClickListener(v -> dismiss());
    }


    private void checkInstallPermission() {
        //1.先判断有没有安装权限---适配8.0
        //如果不想用封装好的，可以自己去实现8.0适配
        InstallUtils.checkInstallPermission((Activity) context, new InstallUtils.InstallPermissionCallBack() {
            @Override
            public void onGranted() {
                downloadApk();
            }

            @Override
            public void onDenied() {
                //弹出弹框提醒用户
                AlertDialog alertDialog = new AlertDialog.Builder(context)
                        .setTitle("温馨提示")
                        .setMessage("必须授权才能安装APK，请设置允许安装")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //打开设置页面
                                InstallUtils.openInstallPermissionSetting((Activity) context, new InstallUtils.InstallPermissionCallBack() {
                                    @Override
                                    public void onGranted() {
                                        downloadApk();
                                    }

                                    @Override
                                    public void onDenied() {
                                        ToastUtil.showToast("不允许安装咋搞？强制更新就退出应用程序吧！");
                                    }
                                });
                            }
                        })
                        .create();

                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);

                alertDialog.show();
            }
        });
    }


    private void downloadApk() {
        rectProgressBar.setVisibility(VISIBLE);
        String filePath = getExternalCacheDirPath();
       // String APK_URL_01 = updateRes.getAppDownloadUrl();
        String APK_URL_01 = "https://mxt.nmgwolf.com/dload09/mxt-picc-6.4.apk";
        InstallUtils.with(context)
                .setApkUrl(APK_URL_01)
                //非必须-下载保存的文件的完整路径+/name.apk，使用自定义路径需要获取读写权限
                .setApkPath(filePath + "/cows.apk")
                .setCallBack(new InstallUtils.DownloadCallBack() {
                    @Override
                    public void onStart() {
                        //下载开始
                        btn_update.setVisibility(GONE); // 升级时隐藏升级按钮防止重复点击
                    }

                    @Override
                    public void onComplete(String path) {
                        //下载完成
                        initAPK(filePath + "/cows.apk");
                    }

                    @Override
                    public void onLoading(long total, long current) {
                        //下载中
                        rectProgressBar.setProgress((int) (((double)current / total)*100));
                    }

                    @Override
                    public void onFail(Exception e) {
                        //下载失败
                    }

                    @Override
                    public void cancle() {
                        //下载取消
                    }
                })
                //开始下载
                .startDownload();
    }

    public String getExternalCacheDirPath() {
        File externalCacheDir;
        // 首先检查是否有外部存储并且可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 尝试获取外部缓存目录
            externalCacheDir = context.getExternalCacheDir();
        } else {
            // 如果外部存储不可用，尝试获取内部缓存目录
            externalCacheDir = context.getCacheDir();
        }
        // 返回文件路径作为字符串
        return externalCacheDir.getAbsolutePath();
    }


    /**
     * 安装APK工具类
     */
    private void initAPK(String path) {
        InstallUtils.installAPK((Activity) context, path, new InstallUtils.InstallCallBack() {
            @Override
            public void onSuccess() {
                //onSuccess：表示系统的安装界面被打开
                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                Toast.makeText(context, "正在安装程序", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFail(Exception e) {
                Toast.makeText(context, "安装失败:" + e.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
